package com.stendahls.groupbot;

import com.google.wave.api.*;


public class GroupbotServlet extends AbstractRobotServlet {

    private final String BOT_NAME = "stendahlsnet-group@appspot.com";

    private final String MSG_WELCOME = "Hi!";


    @Override
    public void processEvents(RobotMessageBundle robotMessageBundle) {
        Wavelet wavelet = robotMessageBundle.getWavelet();
        for (Event event : robotMessageBundle.getEvents()) {

            Blip currentBlip = event.getBlip();
            switch(event.getType()) {
                case WAVELET_SELF_ADDED:
                    wavelet.setTitle(MSG_WELCOME);
                    break;
                case BLIP_SUBMITTED:
                    if (!isRoot(currentBlip, wavelet)) {
                        String text = currentBlip.getDocument().getText();

                        if(CommandFactory.isCommand(text)) {
                            Command command = CommandFactory.find(text);

                            if(command != null) {
                                command.perform(robotMessageBundle);
                            } else {
                                wavelet.appendBlip().getDocument().append(
                                        String.format("Uknown command: '%s', try %s for list of commands", text, "#help")
                                );
                            }
                        }


                    }
                    break;
                case WAVELET_PARTICIPANTS_CHANGED:
                    for (String participant : event.getAddedParticipants()) {
                        if (!participant.equals(BOT_NAME) &&
                                !participant.equals(wavelet.getCreator())) {
                            wavelet.appendBlip().getDocument().append("Hi " + participant + "!");
                        }
                    }
                    break;
                case FORM_BUTTON_CLICKED:
                    break;
            }
        }
    }

    private boolean isRoot(Blip blip, Wavelet wavelet) {
        return blip.getBlipId().equals(wavelet.getRootBlipId());
    }


}

